package com.af.community.smart.business

import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import com.af.community.smart.base.*
import com.af.community.smart.model.HouseData
import com.af.community.smart.utils.*
import com.af.community.smart.viewmodel.HouseViewModel
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import kotlinx.android.synthetic.main.layout_title_search.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.koin.androidx.viewmodel.ext.android.getViewModel

class HouseListActivity : BaseActivity() {

    private var mKey = ""
    private var mVillageId = ""
    private var mBuildId = ""
    private var mCellName = ""
    private var mFloorName = ""
    private var mRoomName = ""
    private var isPatrol = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_house_list)
        setToolbarVisibility(false)
        initTitle()

        swipe_refresh.isRefreshing = true
        getData(pageNum)

        observe("house_state") { updateList() }
    }

    override fun getViewModel() = getViewModel<HouseViewModel>()

    override fun initTitle(title: String, name: String) {
        mVillageId = intent.getStringExtra("villageId").orEmpty()
        mBuildId = intent.getStringExtra("buildId").orEmpty()
        mCellName = intent.getStringExtra("cellName").orEmpty()
        mFloorName = intent.getStringExtra("floorName").orEmpty()
        mRoomName = intent.getStringExtra("roomName").orEmpty()
        isPatrol = intent.getBooleanExtra("isPatrol", false)

        search_edit.hint = "请输入名称、房主姓名、住房编号"
        empty_hint.text = "暂无相关房屋信息！"
        swipe_refresh.refresh { getData(1) }
        recycle_list.loadLinear(baseContext, swipe_refresh) {
            if (!isLoadingMore) {
                isLoadingMore = true
                getData(pageNum)
            }
        }

        mAdapter = SlimAdapter.create()
            .register<HouseData>(R.layout.item_house_list) { data, injector ->

                val map = HashMap<String, String?>()
                when (data.houseType) {
                    "ht_zf" -> {
                        map["hint1"] = "房主姓名："
                        map["hint2"] = "住房编号："
                        map["value1"] = data.ownerName
                        map["value2"] = data.code
                    }
                    "ht_czf" -> {
                        map["hint1"] = "房东姓名："
                        map["hint2"] = "住房编号："
                        map["value1"] = data.ownerName
                        map["value2"] = data.code
                    }
                    "ht_zjcs" -> {
                        map["hint1"] = "场所名称："
                        map["hint2"] = "所属宗教："
                        map["value1"] = data.name
                        map["value2"] = data.religion
                    }
                    "ht_yldw" -> {
                        map["hint1"] = "单位名称："
                        map["hint2"] = "单位性质："
                        map["value1"] = data.name
                        map["value2"] = data.unitsOwnership
                    }
                    "ht_xzdw" -> {
                        map["hint1"] = "单位名称："
                        map["hint2"] = "单位法人："
                        map["value1"] = data.name
                        map["value2"] = data.personCharge
                    }
                    "ht_xhhzz", "ht_xjjzz" -> {
                        map["hint1"] = "组织名称："
                        map["hint2"] = "组织类别："
                        map["value1"] = data.name
                        map["value2"] = data.type
                    }
                    "ht_zacs", "ht_xfaq" -> {
                        map["hint1"] = "场所名称："
                        map["hint2"] = "场所类型："
                        map["value1"] = data.name
                        map["value2"] = data.type
                    }
                    "ht_aqsc", "ht_qy" -> {
                        map["hint1"] = "企业名称："
                        map["hint2"] = "企业类型："
                        map["value1"] = data.name
                        map["value2"] = data.type
                    }
                    "ht_xx" -> {
                        map["hint1"] = "学校名称："
                        map["hint2"] = "学校类型："
                        map["value1"] = data.name
                        map["value2"] = data.unitsOwnership
                    }
                    else -> {
                        map["hint1"] = "场所名称："
                        map["hint2"] = "场所类型："
                        map["value1"] = data.name
                        map["value2"] = data.unitsOwnership
                    }
                }

                injector.text(R.id.item_house_grid, data.gridName)
                    .text(R.id.item_house_type, data.houseTypeName)
                    .text(R.id.item_house_hint1, map["hint1"])
                    .text(R.id.item_house_hint2, map["hint2"])
                    .text(R.id.item_house_name, map["value1"])
                    .text(R.id.item_house_num, map["value2"])
                    .clicked(R.id.item_house) {
                        if (data.houseType.isNullOrEmpty()) return@clicked

                        startActivity<HouseDetailActivity>(
                            "isPatrol" to isPatrol,
                            "houseId" to data.id,
                            "houseType" to data.houseType,
                            "houseName" to data.houseTypeName
                        )
                    }
            }
            .attachTo(recycle_list)

        search_close.oneClick { search_edit.setText("") }
        search_edit.addTextChangedListener(this@HouseListActivity)
        search_edit.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                hideSoftInput() //隐藏软键盘

                if (search_edit.text.isBlank()) {
                    toast("请输入关键字")
                } else {
                    mKey = search_edit.trimString()
                    updateList()
                }
            }
            return@setOnEditorActionListener false
        }

        search_right.oneClick {
            hideSoftInput() //隐藏软键盘

            if (search_edit.text.isBlank()) {
                toast("请输入关键字")
            } else {
                mKey = search_edit.trimString()
                updateList()
            }
        }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().getHouseList(
            "name" to mKey,
            "size" to 20,
            "page" to index,
            "gridId" to getString("gridId"),
            "villageId" to mVillageId,
            "buildId" to mBuildId,
            "cellName" to mCellName,
            "floorName" to mFloorName,
            "roomName" to mRoomName
        )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mList.apply {
                        if (index == 1) {
                            clear()
                            pageNum = index
                        }
                        addItems(it)
                        if (count(it) > 0) pageNum++
                    }

                    mAdapter.updateData(mList)
                },
                onFinally = {
                    swipe_refresh.isRefreshing = false
                    isLoadingMore = false
                    empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                }
            )
    }

    private fun updateList() {
        swipe_refresh.isRefreshing = true

        empty_view.gone()
        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        pageNum = 1
        getData(pageNum)
    }

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        search_close.visibility = if (s.isEmpty()) View.GONE else View.VISIBLE
        if (s.isEmpty() && mKey.isNotEmpty()) {
            mKey = ""
            updateList()
        }
    }

}
